<?php
declare (strict_types=1);

namespace app\controller\v1;

use app\model\BaseModel;
use app\serviceapp\UserService;
use app\util\SmsHelper;
use app\util\ValidateHelper;
use think\annotation\route\Group;
use think\annotation\Route;
use think\facade\Cache;
use think\facade\Env;

/**
 * 用户
 * Class User
 * @package app\controller\v1
 * @Group("v1/user")
 */
class User extends Base
{
    /**
     * 手机号登录&注册
     * @Route("loginByPhone", method="POST")
     */
    public function loginByPhone()
    {
        // todo redis
        $phone = $this->request->post("phone", '', "intval");
        $vcode = $this->request->post("vcode", '', "intval");
        $module = $this->request->post("module", 'login', "trim");
        $env = Env::get('APP_ENV');

        if (ValidateHelper::isMobile($phone) == false || $vcode <= 0) {
            throw new \app\MyException(10004);
        }

        if ($env == 'test') {
            if ($vcode != '123456') {
                throw new \app\MyException(12012);
            }
        } else {
            if ($phone == '15701584942') {
                if ($vcode != '123456') throw new \app\MyException(12012);
            } else {
                if (SmsHelper::checkVcode($phone, $vcode, $module) == false) {
                    throw new \app\MyException(12012);
                }
            }
        }

        $cacheKey = config('cachekeys.user_reg') . $phone;
        $isLock = commitCheck($cacheKey);
        if (!$isLock) {
            throw new \app\MyException(10013);
        }

        BaseModel::beginTrans();
        try {
            $userData = UserService::loginByPhone($phone, $module);
            BaseModel::commitTrans();
            // 删除redis
            SmsHelper::clearCacheKey($phone, $module);
            SmsHelper::clearLoginCacheKey($userData['userId']);
            unset($userData['userId']);
        } catch (\Exception $ex) {
            BaseModel::rollbackTrans();
            throw new \app\MyException(10005, "接口异常:" . $ex->getMessage());
        }
        return json_ok($userData, 0);
    }

    /**
     * APP微信登录
     * @Route("loginByWechat", method="POST")
     * @return array
     */
    public function loginByWechat()
    {
        // todo redis
        $avatar = $this->request->post("avatar", '', "trim");
        $gender = $this->request->post("gender", '', 'trim');
        $nick_name = $this->request->post("nickName", '', 'trim');
        $openid = $this->request->post("openid", '', "trim");
        $unionid = $this->request->post("unionid", '', "trim");
        if (empty($unionid)) {
            throw new \app\MyException(10002);
        }
        if (empty($nick_name)) {
            $nick_name = UserService::getRegisterName();
        }

        BaseModel::beginTrans();
        try {
            $data['avatar'] = $avatar;
            $data['sex'] = $gender;
            $data['openid'] = $openid;
            $data['unionid'] = $unionid;
            $data['nick_name'] = $nick_name;
            $userData = UserService::loginByWechat($data);
            SmsHelper::clearLoginCacheKey($userData['userId']);
            unset($userData['userId']);
            BaseModel::commitTrans();
        } catch (\Exception $ex) {
            BaseModel::rollbackTrans();
            throw new \app\MyException(10005, "接口异常:" . $ex->getMessage());
        }
        return json_ok($userData, 0);
    }

    /**
     * 小程序授权登录
     * @Route("loginByMinWechat", method="POST")
     * @return array
     */
    public function loginByMinWechat()
    {
        BaseModel::beginTrans();
        try {
            $code = $this->request->post("code", '', "trim");
            $avatar = $this->request->post("avatar", '', "trim");
            $gender = $this->request->post("gender", 0, "intval");
            $nick_name = $this->request->post("nickName", '', "trim");
            $iv = $this->request->post("iv", '', "trim");
            $encryptedData = $this->request->post("encryptedData", '', "trim");
            if (empty($code) || empty($iv) || empty($encryptedData)) {
                throw new \app\MyException(10002);
            }

            if (empty($nick_name)) {
                $nick_name = UserService::getRegisterName();
            }
            $data['avatar'] = $avatar;
            $data['sex'] = $gender;
            $data['code'] = $code;
            $data['nick_name'] = $nick_name;
            $data['iv'] = $iv;
            $data['encryptedData'] = $encryptedData;
            $userData = UserService::loginByMinWechat($data);
            SmsHelper::clearLoginCacheKey($userData['userId']);
            unset($userData['userId']);
            BaseModel::commitTrans();
        } catch (\Exception $ex) {
            BaseModel::rollbackTrans();
            throw new \app\MyException(10005, "接口异常:" . $ex->getMessage());
        }

        return json_ok($userData, 0);
    }

    /**
     * 用户详情
     * @Route("userDetail", method="POST")
     */
    public function userDetail()
    {
        // todo redis
        $user = $this->request->dani_user;
        if (empty($user)) {
            throw new \app\MyException(10004);
        }
        $userId = $user['user_id'];
        if (empty($userId)) {
            throw new \app\MyException(10004);
        }
        $userInfo = UserService::getUserInfo($userId);
        return json_ok($userInfo, 0);
    }

    /**
     * 退出登录
     * @Route("loginOut", method="POST")
     */
    public function loginOut()
    {
        $user = $this->request->dani_user;
        if (empty($user)) {
            throw new \app\MyException(10004);
        }
        $cacheKey = config('cachekeys.acc_key') . $user['user_id'];
        Cache::set($cacheKey, 1);
        return json_ok((object)[], 0);
    }
}
